import 'package:flutter/material.dart';
import 'package:flutterdemo/0demo/ui/animated_wrapper/common/animated_wrapper_common.dart';

class AnimatedWrapper extends StatefulWidget {
  final double wrapperWidth;
  final double itemWidth;
  final double itemHeight;

  const AnimatedWrapper(this.itemWidth, this.itemHeight, this.wrapperWidth, {Key key})
      : super(key: key);

  @override
  State<AnimatedWrapper> createState() => _AnimatedWrapperState();
}

class _AnimatedWrapperState extends State<AnimatedWrapper> {
  final _movingItemKey = GlobalKey<MovingItemState>();
  List<Widget> _items = [];

  List<ItemModel> _modelList = [];

  @override
  void initState() {
    int count = 10;
    for (int i = 0; i < count; i++) {
      _modelList.add(ItemModel(randomColor()));
    }
    _updateItems();
    super.initState();
  }

  // change by model list
  _updateItems() {
    _items = [];
    for (int i = 0; i < _modelList.length; i++) {
      _items.add(_getItem(_modelList[i]));
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        width: widget.wrapperWidth,
        height: 1000,
        child: Stack(
          children: [
            Wrap(
              children: _items,
            ),
            MovingItem(
              widget.itemWidth,
              _items.length,
              key: _movingItemKey,
              onMoveComplete: (model) async {
                await Future.delayed(Duration(milliseconds: 100));
                // append
                // _modelList.removeWhere((element) => element.color == model.color);
                _modelList.add(ItemModel(model.color));
                _updateItems();
                // dismiss origin

                // visible
                _movingItemKey.currentState.show(false);
              },
            ),
          ],
        ));
  }

  Widget _getItem(ItemModel model) {
    int index = _modelList.lastIndexWhere((element) => element.color == model.color);
    return Item(
      widget.itemWidth,
      model,
      dismissDuration: 100,
      onMove: (model) {
        _modelList.removeWhere((element) => element.color == model.color);
        _updateItems();
        _movingItemKey.currentState.show(true);
        _movingItemKey.currentState.startMove(model, index);
      },
    );
  }
}
